<template>
  <div id="Manage">
    <h1 class="text-3xl font-bold text-center my-8">管理页面</h1>
    <div class="button-group">
      <el-button @click="activeTab = 'users'">用户列表</el-button>
      <el-button @click="activeTab = 'posts'">帖子列表</el-button>
      <el-button @click="activeTab = 'comments'">评论列表</el-button>
      <el-button @click="activeTab = 'messages'">私信列表</el-button>
      <el-button @click="activeTab = 'zones'">专区列表</el-button>
    </div>

    <el-card v-if="activeTab === 'users'">
      <template #header>
        <div class="flex justify-between items-center">
          <span>用户列表</span>
        </div>
      </template>
      <el-input v-model="userSearch" placeholder="搜索用户" class="ml-4 small-input" size="small"></el-input> <el-button color="pink" @click="getusers()">查询</el-button>
      <el-table :data="currentUserList">
        <el-table-column prop="avator" label="头像">
          <template #default="scope">
            <el-avatar :src="scope.row.avator"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="support" label="点赞量"></el-table-column>
        <el-table-column prop="personalSignature" label="个人签名"></el-table-column>
        <el-table-column prop="userTime" label="注册时间"></el-table-column>
        <el-table-column prop="id" label="操作">
          <template #default="scope">
            <el-button v-if="scope.row.ban" @click="Noban(scope.row.id)" color="green">解封</el-button>
            <el-button v-else  @click="ban(scope.row.id) " color="red">封禁</el-button>
          
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="userList.length"
    >
    </el-pagination>
    </el-card>

    <el-card v-if="activeTab === 'posts'">
      <template #header>
        <div class="flex justify-between items-center">
          <span>帖子列表</span>
        </div>
      </template>
      <el-input v-model="postSearch" placeholder="搜索用户" class="ml-4 small-input" size="small"></el-input> <el-button color="pink" @click="getPostList()">查询</el-button>
      <el-table :data="currentPostList">
        <el-table-column prop="postId" label="ID"></el-table-column>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="postContent" label="内容">
            <template #default="scope">
            <div v-html="scope.row.postContent"></div>
          </template>
        </el-table-column>
        <el-table-column prop="support" label="点赞量"></el-table-column>
        <el-table-column prop="user.username" label="作者"></el-table-column>
        <el-table-column prop="time" label="时间"></el-table-column>
        <el-table-column prop="postId" label="操作">
          <template #default="scope">
            <el-button  @click="deletePost(scope.row.postId)" color="red">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="postList.length"
    >
    </el-pagination>
    </el-card>

    <el-card v-if="activeTab === 'comments'">
      <template #header>
        <div class="flex justify-between items-center">
          <span>评论列表</span>
        </div>
      </template>
      <el-input v-model="commentSearch" placeholder="搜索用户" class="ml-4 small-input" size="small"></el-input> <el-button color="pink" @click="getCommentList()">查询</el-button>
      <el-table :data="currentCommentList">
        <el-table-column prop="commentId" label="ID"></el-table-column>
        <el-table-column prop="content" label="内容">
            <template #default="scope">
            <div v-html="scope.row.content"></div>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="评论者"></el-table-column>
        <el-table-column prop="commentSupport" label="点赞量"></el-table-column>
        <el-table-column prop="commentTime" label="点赞时间"></el-table-column>
        <el-table-column prop="commentId" label="操作">
          <template #default="scope">
            <el-button  @click="deleteComment(scope.row.commentId)" color="red">删除</el-button>
          </template>
        </el-table-column>
        
      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="commentList.length"
    >
    </el-pagination>
    </el-card>

    <el-card v-if="activeTab === 'messages'">
      <template #header>
        <div class="flex justify-between items-center">
          <span>私信列表</span>
        </div>
      </template>
      <el-input v-model="chatSearch" placeholder="搜索私信" class="ml-4 small-input" size="small"></el-input> <el-button color="pink" @click="getChatList()">查询</el-button>
      <el-table :data="currentChatList">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column label="发件人">
          <template #default="scope">
            {{ scope.row.senderName }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="私信内容"></el-table-column>
        <el-table-column prop="createTime" label="时间"></el-table-column>
        <el-table-column prop="commentId" label="操作">
          <template #default="scope">
            <el-button  @click="deleteChat(scope.row.id)" color="red">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="chatList.length"
    >
    </el-pagination>
    </el-card>

    <el-card v-if="activeTab === 'zones'">
    <template #header>
      <div class="flex justify-between items-center">
        <span>专区列表</span>
      </div>
    </template>
    <el-input v-model="zoneSearch" placeholder="搜索专区" class="ml-4 small-input" size="small"></el-input>
    <el-button color="pink" @click="getZoneList()">查询</el-button>
    <el-button color="green" @click="openAddZone()">新增专区</el-button>
    <el-table :data="currentZoneList">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="专区名称"></el-table-column>
      <el-table-column label="版块列表">
        <template #default="scope">
          <div v-if="scope.row.sectionList && scope.row.sectionList.length > 0">
            <div v-for="(section, index) in scope.row.sectionList" :key="index">
              <span>{{ section.introduce }}</span>
              <el-button @click="deleteSection(scope.row.id, section.sectionId)" color="red" size="mini">删除</el-button>
            </div>
          </div>
          <div v-else>暂无版块</div>
        </template>
      </el-table-column>
      <el-table-column prop="zoneId" label="操作">
        <template #default="scope">
          <el-button @click="deleteZone(scope.row.id)" color="red">删除</el-button>
          <el-button @click="openAddSection(scope.row.id)" color="green">新增版块</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="zoneList.length"
    >
    </el-pagination>
  </el-card>

  <el-dialog
        v-model="addZoneDialogVisible"
        title="新增专区"
        width="30%"
      >
        <template #content>
          
        </template>
        <template #footer>
          <el-input v-model="newZone" placeholder="请输入专区名"></el-input>
          
          <span class="dialog-footer">
            <el-button @click="addZoneDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addZone()">新增</el-button>
          </span>
        </template>
      </el-dialog> 

      <el-dialog
        v-model="addSectionDialogVisible"
        title="新增版块"
        width="30%"
      >
        <template #content>
          
        </template>
        <template #footer>
          <el-input v-model="newSection" placeholder="请输入版块名"></el-input>
          <input type="file" @change="sendImage" accept="image/*">
          <span class="dialog-footer">
            <el-button @click="addSectionDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addSection()">新增</el-button>
          </span>
        </template>
      </el-dialog> 

  </div>
</template>

<script setup>
import { onMounted, reactive ,ref,toRaw,computed} from "vue";
import axios from 'axios';
import { userConfig,config } from "@/config/config";
import router from "@/route/Index";
let data = [];
let zones = reactive([]);
let userSearch=ref('')
let postSearch=ref('')
let commentSearch=ref('')
let chatSearch=ref('')
let zoneSearch=ref('')
let userList=ref('')
const activeTab = ref('users');
let postList=ref()
let commentList=ref()
let chatList=ref()
let zoneList=ref()
let newZone=ref()
let newSection=ref()
let selectZoneId=ref()

const currentPage = ref(1);
const pageSize = ref(10);
let addZoneDialogVisible=ref(false)
let addSectionDialogVisible=ref(false)
let imgurl = ref('')

onMounted(() => {

getusers()
getPostList()
getCommentList()
getChatList()
getZoneList()
});

const getusers=()=>{
  let userDto={
    username:userSearch.value
  }
    axios.post("api/Manage/getUserList",userDto,config).then(function(response){
        userList.value=response.data.data
        //userList.value=userList.value.data
        console.log(userList.value)
        currentPage.value = 1; 
    })
}
const getPostList=()=>{
  let postDto={
    postContent:postSearch.value
  }
    axios.post("api/Manage/getPostList",postDto,config).then(function(response){
        postList.value=response.data.data
        //postList.value=postList.value.data
        console.log(postList.value)
    })
}
const getCommentList=()=>{
  let commentDto={
    content:commentSearch.value
  }
  axios.post("api/Manage/getCommentList",commentDto,config).then(function(response){
    commentList.value=response.data.data
        //postList.value=postList.value.data
        console.log(commentList.value)
    })
}
const getChatList=async()=>{
  let messageDto={
    content:chatSearch.value
  }
  await axios.post("api/Manage/getChatList",messageDto,config).then(function(response){
    chatList.value=response.data.data
        //postList.value=postList.value.data
        console.log(chatList.value)
    })
}

const getZoneList=async()=>{
  let zoneDto={
    name:zoneSearch.value
  }
  await axios.post("api/Manage/getZoneList",zoneDto,config).then(function(response){
    zoneList.value=response.data.data
        //postList.value=postList.value.data
        console.log(zoneList.value)
    })
}

const addZone=async()=>{
  let zoneDto={
   name:newZone.value,
   master:localStorage.getItem("username")
  }
  axios.post("api/Manage/addZone",zoneDto,config).then(function (response){
    if(response.status==200){
      openAddZone.value=false
      getZoneList()

    }
    else{
      alert("操作失败")
      openAddZone.value=false
    }
  })
}


const ban=(userId)=>{
    let userDto={
        id:userId
    }
    axios.post("api/Manage/ban",userDto,config).then(function (response){
        if(response.status==200){
            getusers()
        }else{
            alert("操作失败")
        }
    })
}
const Noban=(userId)=>{
    let userDto={
        id:userId
    }
    axios.post("api/Manage/Noban",userDto,config).then(function (response){
        if(response.status==200){
            getusers()
        }else{
            alert("操作失败")
        }
    })
}

const deletePost=(postId)=>{
    let postDto={
        postId:postId
    }
    axios.post("api/Manage/deletePost",postDto,config).then(function (response){
        if(response.status==200){
            getPostList()
        }else{
            alert("操作失败")
        }
    })
}

const deleteComment=(commentId)=>{
  let commentDto={
    commentId:commentId
    }
    axios.post("api/Manage/deleteComment",commentDto,config).then(function (response){
        if(response.status==200){
          getCommentList()
        }else{
            alert("操作失败")
        }
    })
}

const deleteChat=(messageid)=>{
  let messageDto={
    id:messageid
  }
  axios.post("api/Manage/deleteChat",messageDto,config).then(function (response){
        if(response.status==200){
          getChatList()
        }else{
            alert("操作失败")
        }
    })
}

const openAddZone=()=>{
  addZoneDialogVisible.value=true
}

const openAddSection=(id)=>{
  selectZoneId.value=id
  addSectionDialogVisible.value=true
}

const deleteZone=(zoneId)=>{
  let zoneDto={
    id:zoneId
  }
  axios.post("api/Manage/deleteZone",zoneDto,config).then(function(response){
    if(response.status==200){
      alert("操作成功")
      getZoneList()
    }else{
      alert("操作失败")
    }
  })
}
const addSection=()=>{
  let sectionDto={
    sectionName:newSection.value,
    introduce:newSection.value,
    zoneId:selectZoneId.value,
    sectionMaster:localStorage.getItem("username"),
    img:imgurl.value,
  }
  if(newSection.value=''||imgurl.value==''){
    alert("请输入板块名和图片")
  }else{
    axios.post("api/Manage/addSection",sectionDto,config).then(function(response){
    if(response.status==200){
      addSectionDialogVisible.value=false
    }else{
      alert("操作失败")
    }
  })
  }
 
}

const deleteSection=(zid,sid)=>{
  console.log(zid+"和"+sid)
  let sectionDto={
    sectionId:sid
  }
  axios.post("api/Manage/deleteSection",sectionDto,config).then(function(response){
    if(response.status==200){
     getZoneList()
    }else{
      alert("操作失败")
    }
  })
}

const sendImage = (event) => {
    const file = event.target.files[0];
    if (file ) {
      const reader = new FileReader();
      reader.onload = async (e) => {
      const url= await handleFileChange(file)
       // 替换为你的七牛云存储空间域名
const domain = 'http://svftekle7.hn-bkt.clouddn.com';
// 拼接最终的 URL
const finalUrl =url;
imgurl.value=finalUrl
      };
      reader.readAsDataURL(file);
    }
  };

const handleFileChange = async (rawFile) => {
    const file = rawFile;
    console.log("选择文件已触发")
    if (file) {
      console.log("已找到文件")
      const qiniuKey = await uploadAvatarToQiniu(file);
      if (qiniuKey) {
        console.log("开始上传")
        const domain = 'http://svftekle7.hn-bkt.clouddn.com'; // 替换为你的七牛云存储空间域名
        const avatarUrl = `${qiniuKey}`;
        //await sendAvatarUrlToBackend(avatarUrl);
        return domain+"/"+avatarUrl
      }
    }
  };

  // 从后端获取上传凭证的函数，这里假设你有一个后端接口可以返回 token
const getUploadToken = async () => {
  try {
    let userDto={

    }
    const response = await axios.post('api/user/getQiniuToken',userDto,config)
    console.log(response)
    return response.data.data
    
  } catch (error) {
    console.error('获取上传凭证失败:', error);
    return null;
  }
};
let QiniuToken=ref()

// 上传头像到七牛云的函数
const uploadAvatarToQiniu = async (file) => {
  const token = await getUploadToken();
  QiniuToken.value=token;
  if (!token) {
    console.log("没有token",token)
    return;
  }

  const formData = new FormData();
  formData.append('token', token);
  formData.append('file', file);

  try {
    const response = await axios.post('https://up-z2.qiniup.com', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log('上传到七牛云成功:', response.data);
    return response.data.key;
  } catch (error) {
    console.error('上传到七牛云失败:', error);
    return null;
  }
};

// 将图片地址发送给后端的函数
// const sendAvatarUrlToBackend = async (url) => {
//   try {
//     User.value.avator=url
//     const response = await axios.post('api/user/changeAvater', User.value);
//     console.log('头像地址发送给后端成功:', response.data);
//     window.location.reload();
//     return response.data;
//   } catch (error) {
//     console.error('头像地址发送给后端失败:', error);
//     return null;
//   }
// };



const currentUserList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return userList.value.slice(start, end);
});

const currentPostList=computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return postList.value.slice(start, end);
});

const currentCommentList=computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return commentList.value.slice(start, end);
});

const currentChatList=computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return chatList.value.slice(start, end);
});

const currentZoneList=computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return zoneList.value.slice(start, end);
});
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};





</script>

<style scoped>
.button-group {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
.small-input {
  width: 320px; /* 你可以根据需要调整宽度 */
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>  
